package com.ruoyi.business.controller;

import java.io.IOException;
import java.util.List;

import com.ruoyi.business.domain.JtCountryCode;
import com.ruoyi.business.domain.JtProduct;
import com.ruoyi.business.domain.JtProductCategory;
import com.ruoyi.business.service.IJtCountryCodeService;
import com.ruoyi.business.service.IJtProductCategoryService;
import com.ruoyi.business.utils.ProductUtil;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.utils.JtImageUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.JtProductPublish;
import com.ruoyi.business.service.IJtProductPublishService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 发布产品信息Controller
 * 
 * @author Alan Zhang
 * @date 2025-04-22
 */
@Controller
@RequestMapping("/business/publish")
public class JtProductPublishController extends BaseController
{
    private String prefix = "business/publish";

    @Autowired
    private IJtProductPublishService jtProductPublishService;
    @Autowired
    private IJtCountryCodeService jtCountryCodeService;
    @Autowired
    private IJtProductCategoryService productCategoryService;
    @Autowired
    private ServerConfig serverConfig;

    @RequiresPermissions("business:publish:view")
    @GetMapping()
    public String publish(ModelMap mmap)
    {
        findData(mmap);

        return prefix + "/publish";
    }

    private void findData(ModelMap mmap){
        //分类
        JtProductCategory paramCategory = new JtProductCategory();
        List<JtProductCategory> categoryList = productCategoryService.selectJtProductCategoryList(paramCategory);
        mmap.put("categoryList", categoryList);

        //发布地区
        JtCountryCode paramCountry = new JtCountryCode();
        List<JtCountryCode> countryCodeList = jtCountryCodeService.selectJtCountryCodeList(paramCountry);
        mmap.put("publishRegionList", countryCodeList);
    }

    /**
     * 查询发布产品信息列表
     */
    @RequiresPermissions("business:publish:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(JtProductPublish jtProductPublish)
    {
        startPage();
        List<JtProductPublish> list = jtProductPublishService.selectJtProductPublishList(jtProductPublish);
        return getDataTable(list);
    }

    /**
     * 导出发布产品信息列表
     */
    @RequiresPermissions("business:publish:export")
    @Log(title = "发布产品信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(JtProductPublish jtProductPublish)
    {
        List<JtProductPublish> list = jtProductPublishService.selectJtProductPublishList(jtProductPublish);
        ExcelUtil<JtProductPublish> util = new ExcelUtil<JtProductPublish>(JtProductPublish.class);
        return util.exportExcel(list, "发布产品信息数据");
    }

    /**
     * 新增发布产品信息
     */
    @RequiresPermissions("business:publish:add")
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        findData(mmap);
        return prefix + "/add";
    }

    /**
     * 新增保存发布产品信息
     */
    @RequiresPermissions("business:publish:add")
    @Log(title = "发布产品信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult addSave(JtProductPublish jtProductPublish, MultipartFile file) throws IOException {
        if(StringUtils.isNotEmpty(jtProductPublish.getStyleNo())){
            boolean res = ProductUtil.checkProductNo(jtProductPublish.getStyleNo());
            if(res){
                return AjaxResult.error("款式编码不能包含特殊字符：逗号、空格");
            }
        }
        JtProductPublish param = new JtProductPublish();
        param.setProductTitle(jtProductPublish.getProductTitle());
        param.setStyleNo(jtProductPublish.getStyleNo());
        param.setPublishCountryCode(jtProductPublish.getPublishCountryCode());
        List<JtProductPublish> productPublishList = jtProductPublishService.selectJtProductPublishList(param);
        if(productPublishList.size() > 0){
            return AjaxResult.error(jtProductPublish.getStyleNo() + "已存在！");
        }

        if (file != null) {
            jtProductPublish.setImageUrl(JtImageUtil.uploadProduct(file, true));
        }
        if (file != null) {
            jtProductPublish.setImageUrl(JtImageUtil.uploadProductThumbnail(file, true));
        }
        return toAjax(jtProductPublishService.insertJtProductPublish(jtProductPublish));
    }

    /**
     * 修改发布产品信息
     */
    @RequiresPermissions("business:publish:edit")
    @GetMapping("/edit/{productId}")
    public String edit(@PathVariable("productId") Long productId, ModelMap mmap)
    {
        findData(mmap);

        JtProductPublish jtProductPublish = jtProductPublishService.selectJtProductPublishByProductId(productId);
        mmap.put("jtProductPublish", jtProductPublish);
        return prefix + "/edit";
    }

    /**
     * 修改保存发布产品信息
     */
    @RequiresPermissions("business:publish:edit")
    @Log(title = "发布产品信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editSave(JtProductPublish jtProductPublish, String removeSkuIds, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        if(StringUtils.isNotEmpty(jtProductPublish.getStyleNo())){
            boolean res = ProductUtil.checkProductNo(jtProductPublish.getStyleNo());
            if(res){
                return AjaxResult.error("款式编码不能包含特殊字符：逗号、空格");
            }
        }
        if (file != null) {
            jtProductPublish.setImageUrl(JtImageUtil.uploadProduct(file, true));

            //删除 图片文件
            JtProductPublish jtProductDb = jtProductPublishService.selectJtProductPublishByProductId(jtProductPublish.getProductId());
            String oldImageUrl = jtProductDb.getImageUrl();
            if(StringUtils.isEmpty(oldImageUrl)){
                JtImageUtil.deleteFile(oldImageUrl);
            }

            jtProductPublish.setThumbnailUrl(JtImageUtil.uploadProductThumbnail(file, true));

            //删除 图片缩略文件
            String oldThumbnailUrl = jtProductDb.getThumbnailUrl();
            if(StringUtils.isEmpty(oldThumbnailUrl)){
                JtImageUtil.deleteFile(oldThumbnailUrl);
            }
        }
        return toAjax(jtProductPublishService.updateJtProductPublish(jtProductPublish, removeSkuIds));
    }

    /**
     * 删除发布产品信息
     */
    @RequiresPermissions("business:publish:remove")
    @Log(title = "发布产品信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(jtProductPublishService.deleteJtProductPublishByProductIds(ids));
    }

    /**
     * 上传图片请求（单个）
     */
    @PostMapping("/upload/image")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadProductDetailPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
}
